var bs = require("browser-sync").create();
const ipcRenderer = require('electron').ipcRenderer;
const autoprefixer = require('autoprefixer')
const readDirSync = require('./lib/readDirSync');
const postcss = require('postcss')
const fs = require("fs");
const babel = require("@babel/core");
const path = require("path");
const chokidar = require('chokidar');
var pug = require('pug');
var pretty = require('pretty');
const port = ipcRenderer.sendSync('get-express-port');

const Imagemin = require('./lib/imagemin')
const uglifyJs = require('./lib/uglifyJs')
const cssMin = require('./lib/cssmin')


let txtAddress = document.getElementById("txt_address");



let txtJsfile = document.getElementById("txt_jsfile");

function _fnStart() {
    let argsObj = {
        files: [txtAddress.value+"/**/*.js",txtAddress.value+"/**/*.css",txtAddress.value+"/**/*.html"]
    }
    bs.init({
        server: {
            baseDir: txtAddress.value,
            directory: true
        },
        port:port,
        open: "external",
        notify: false,
        ui:false,
        ghostMode: false,
        ...argsObj
    },function () {
        document.getElementById("btn_stop").style.display = "inline";
        document.getElementById("btn_start").style.display = "none";
    });

}

function _fnStop() {
    bs.exit();
    document.getElementById("btn_stop").style.display = "none";
    document.getElementById("btn_start").style.display = "inline";
}

function _fnAutoprefixer() {

    readDirSync(txtAddress.value,function (filepath) {
        let fileNameReg = /\.css/g;
        let shouldFormat =  fileNameReg.test(filepath);
        if (shouldFormat) {

            let css = fs.readFileSync(filepath).toString()

            postcss([ autoprefixer ]).process(css).then(scss => {
                fs.writeFile(filepath, scss, error => {
                    if (error) return console.log("写入文件失败,原因是" + error.message);
                    console.log(filepath+"写入成功");
                });
            })

        }
    });
}

function _fnBabelRun() {

    if(txtJsfile.value.replace(/\s/g,'').length<1){
        return;
    }

    readDirSync((txtJsfile.value).trim(),function (filepath) {
        let fileNameReg = /\.js/g;
        let shouldFormat =  fileNameReg.test(filepath);
        if (shouldFormat) {

            babel.transformFile(filepath, {
                presets:[require("@babel/preset-env")],
                retainLines:true
            }, function (err, result) {
                if (err) {
                    console.error(err)
                }

                fs.writeFile(filepath, result.code, error => {
                    if (error) return console.log("写入文件失败,原因是" + error.message);
                    console.log(filepath+"写入成功");
                });
            });
        }
    })
}

function _fnCompressRun() {

    var input = document.getElementById('txt_compress_in').value;
    var output = document.getElementById('txt_compress_out').value;


    readDirSync(input.trim(),function (filepath) {

        var outputPath = output + filepath.replace(input,'').replace(path.basename(filepath),'')

        let fileNameReg = /\.jpg|png|svg|gif/g;
        let shouldFormat =  fileNameReg.test(filepath);
        if (shouldFormat) {
            Imagemin(filepath,outputPath)
        }

        fileNameReg = /\.js/g;
        shouldFormat =  fileNameReg.test(filepath);
        if (shouldFormat) {
            uglifyJs(filepath,outputPath)
        }

        fileNameReg = /\.css/g;
        shouldFormat =  fileNameReg.test(filepath);
        if (shouldFormat) {
            cssMin(filepath,outputPath)
        }


    })


}

var pugWatcher= null;

function _fnPugRun() {

    if(pugWatcher){
        pugWatcher.close()
    }
    pugWatcher = chokidar.watch(txtAddress.value+"/**/*.pug",{
        ignored: /(^|[\/\\])\../
    })
    .on("change",(filepath)=>{
        CompilerPug(filepath)
    }).on("add",(filepath)=>{
        CompilerPug(filepath)
    })
}


function CompilerPug(filepath) {
    var fn = pug.compileFile(filepath)

    let stream = fs.createWriteStream(filepath.replace('.pug','.html'),{
        encoding: 'utf8'
    })

    var html = pretty(fn())

    stream.write(html);
    stream.end();
    stream.on('finish',()=>{
        console.log(filepath)
        html = null;
    })
    stream.on('error',(err)=>{
        console.error(err)
        html = null;
    })

}